/* eslint-disable prettier/prettier */
const RNFS = require('react-native-fs');
const { Platform } = require('react-native');

const pngDir = `${RNFS.DocumentDirectoryPath}/image/practice`; // 假设PNG文件存放在这个路径

// 读取单个文件
function readfile(filename) {
  return new Promise((resolve, reject) => {
    RNFS.readFile(`${pngDir}/${filename}`, 'base64')
      .then(data => {
        resolve({
          [filename.slice(0, filename.lastIndexOf('.'))]: 'data:image/png;base64,' + data,
        });
      })
      .catch(err => reject(err));
  });
}

// 读取PNG文件夹下所有png
function readPngs() {
  return new Promise((resolve, reject) => {
    RNFS.readdir(pngDir)
      .then(files => {
        Promise.all(files.map(filename => readfile(filename)))
          .then(data => resolve(data))
          .catch(err => reject(err));
      })
      .catch(err => reject(err));
  });
}

// 生成js文件
readPngs().then(data => {
  let pngFile = 'module.exports = ' + JSON.stringify(Object.assign({}, ...data));
  RNFS.writeFile(`${RNFS.DocumentDirectoryPath}/Pngs.js`, pngFile)
    .then(() => console.log('File written!'))
    .catch(err => console.error(err));
}).catch(err => {
  console.error(err);
});